package com.zondy.mapgis.android.frag;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PointF;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.zondy.mapgis.android.activity.MapActivity;
import com.zondy.mapgis.android.annotation.Annotation;
import com.zondy.mapgis.android.annotation.AnnotationView;
import com.zondy.mapgis.android.base.BaseFragment;
import com.zondy.mapgis.android.graphic.Graphic;
import com.zondy.mapgis.android.graphic.GraphicImage;
import com.zondy.mapgis.android.graphic.GraphicMultiPoint;
import com.zondy.mapgis.android.graphic.GraphicPolygon;
import com.zondy.mapgis.android.graphic.GraphicPolylin;
import com.zondy.mapgis.android.graphic.GraphicText;
import com.zondy.mapgis.android.graphic.GraphicsOverlay;
import com.zondy.mapgis.android.internal.utils.ToastUtil;
import com.zondy.mapgis.android.mapview.MapView;
import com.zondy.mapgis.android.mapview.MapView.MapViewAnnotationListener;
import com.zondy.mapgis.android.mapview.MapView.MapViewTapListener;
import com.zondy.mapgis.android.utils.MapUtil;
import com.zondy.mapgis.core.geometry.Dot;
import com.zondy.mapgis.core.geometry.GeoPolygon;
import com.zondy.mapgis.core.geometry.Geometry;
import com.zondy.mapgis.core.srs.SRefData;
import com.zondy.mapgis.explorer.MapApplication;
import com.zondy.mapgis.explorer.R;

public class MeasureAreaFrag extends BaseFragment implements OnClickListener,MapViewTapListener,MapViewAnnotationListener
{
	private String TAG = this.getClass().getSimpleName();
	private MapActivity mMapActivity = null;
	private MapView mMapView = null;

	// 添加到地图上的Graphic
	private GraphicsOverlay mGraphicLayer = null;
	private GraphicMultiPoint mGraphicMultiPoint = null;
	private GraphicPolygon mGraphicPolygon = null;
	private GraphicText mGraphicText = null;
	private GraphicPolylin mGraphicPolyLine = null;
	private List<Dot> mDotLst = new ArrayList<Dot>();
	/** 存放距离测量值List **/
	private List<String> mDisLst = new ArrayList<String>();
	private List<Annotation> mAnnotationLst = new ArrayList<Annotation>();

	private Annotation mStartAnnotation = null;
	private Annotation mNextAnnotation = null;
	private AnnotationView annotationView = null;
	private View mCalloutView = null;
	private Bitmap mBlueBmp;
	private Bitmap mRedBmp;
	private GraphicImage mGraphicStartImg = null;
	private Bitmap mStartBmp;

	private TextView mTitleTxt = null;
	private ImageView mRedoBtn = null;

	@Override
	public int bindLayout()
	{
		return R.layout.measure_area_frag;
	}

	@Override
	public void initView(View view)
	{
		mTitleTxt = (TextView) view.findViewById(R.id.title_text);
		mTitleTxt.setText("点击地图开始测量");
		mRedoBtn = (ImageView) view.findViewById(R.id.redo_btn);

		view.findViewById(R.id.title_back).setOnClickListener(this);
		view.findViewById(R.id.finish_measure_btn).setOnClickListener(this);
		mRedoBtn.setOnClickListener(this);

		mBlueBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ico_draw_point_blue);
		mRedBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ico_draw_point_red);
		mStartBmp = BitmapFactory.decodeResource(getResources(), R.drawable.ico_result_location_green);
	}

	@Override
	public void doBusiness(Context mContext)
	{
		mMapActivity = MapApplication.getApp().getMapActivity();
		mMapView = mMapActivity.mMapView;
		mGraphicLayer = mMapView.getGraphicsOverlay();
		SRefData sRefData = mMapView.getMap().getSRSInfo();
		
		if(sRefData.getSRSName().equalsIgnoreCase("WGS_84_MCT") || sRefData.getSRSName().equalsIgnoreCase("WGS_1984_Web_Mercator") || sRefData.getSRSName().equalsIgnoreCase("WGS_1984"))
		{
			mMapView.setTapListener(this);
			mMapView.setAnnotationListener(this);
		}
		else
		{
			ToastUtil.showToast(mContext, "暂时不支持该空间参考系测面积");
		}

		if (mGraphicMultiPoint == null)
		{
			mGraphicMultiPoint = new GraphicMultiPoint();
			mGraphicMultiPoint.setColor(Color.BLUE);
			mGraphicMultiPoint.setPointSize(6);
		}
		if (mGraphicPolygon == null)
		{
			mGraphicPolygon = new GraphicPolygon();
			mGraphicPolygon.setPointSize(6);
			mGraphicPolygon.setColor(Color.argb(50, 0, 255, 0));
		}
		if (mGraphicPolyLine == null)
		{
			mGraphicPolyLine = new GraphicPolylin();
			mGraphicPolyLine.setColor(getResources().getColor(R.color.green));
			mGraphicPolyLine.setLineWidth(10.0f);
		}
		if (mGraphicText == null)
		{
			mGraphicText = new GraphicText();
			mGraphicText.setAnchorPoint(new PointF(0.5f, 0.5f));
			mGraphicText.setFontSize(15);
		}
		if (mGraphicStartImg == null)
		{
			mGraphicStartImg = new GraphicImage();
			mGraphicStartImg.setPoint(new Dot(0.0f, 0.0f));
		}
		mGraphicLayer.addGraphic(mGraphicMultiPoint);
		mGraphicLayer.addGraphic(mGraphicPolygon);
		mGraphicLayer.addGraphic(mGraphicPolyLine);
		mGraphicLayer.addGraphic(mGraphicStartImg);
		// mGraphicLayer.addGraphic(mGraphicText);
	}

	@Override
	public void mapViewTap(PointF pointf)
	{
		Dot dot = mMapView.viewPointToMapPoint(pointf);

		if (mDotLst.size() > 3)
		{
			mGraphicPolygon.removePoint(mGraphicPolygon.getPointCount() - 1);
			mDotLst.remove(mDotLst.size() - 1);
		}

		mDotLst.add(dot);

		if (mDotLst.size() == 1)
		{
			mStartAnnotation = MapUtil.addAnnotionByDot(getContext(), mMapView, String.valueOf(mDotLst.size()), "起点", null, mDotLst.get(mDotLst.size() - 1),
					mRedBmp);
			mAnnotationLst.add(mStartAnnotation);
			mStartAnnotation.showAnnotationView();
			updateGraphicImg(mGraphicStartImg, mStartBmp, mDotLst.get(0));
		}
		if (mDotLst.size() == 2)
		{
			mNextAnnotation = MapUtil.addAnnotionByDot(getContext(), mMapView, String.valueOf(mDotLst.size()), "继续点击", null, mDotLst.get(mDotLst.size() - 1),
					mRedBmp);
			mAnnotationLst.add(mNextAnnotation);
			mNextAnnotation.showAnnotationView();
		}

		if (mDotLst.size() > 2)
		{
			mRedoBtn.setVisibility(View.VISIBLE);
			// 区闭合
			mDotLst.add(mDotLst.get(0));
			mGraphicPolygon.setPoints(mDotLst);
			Dot centerDot = mGraphicPolygon.getCenterPoint();
			Geometry geometory = Graphic.toGeometry(mGraphicPolygon);
			if (geometory instanceof GeoPolygon)
			{
				GeoPolygon geoPolygon = (GeoPolygon) geometory;
				mGraphicText.setPoint(centerDot);
				mGraphicText.setText(getArea(geoPolygon));

				mDisLst.add(getArea(geoPolygon));
				mNextAnnotation = MapUtil.addAnnotionByDot(getContext(), mMapView, String.valueOf(mDotLst.size()), getArea(geoPolygon), null,
						mDotLst.get(mDotLst.size() - 2), mRedBmp);
				mAnnotationLst.add(mNextAnnotation);
				mNextAnnotation.showAnnotationView();
				Log.d(TAG, "geoPolygon.calArea():" + geoPolygon.calArea());
				Log.d(TAG, "mGraphicPolygon.getPointCount():" + mGraphicPolygon.getPointCount());
				Log.d(TAG, "mDotLst.size():" + mDotLst.size());
			}
		}

		mGraphicMultiPoint.setPoints(mDotLst);
		mGraphicPolyLine.setPoints(mDotLst);
		mMapView.refresh();
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.finish_measure_btn:
			mMapActivity.removeFragment(TAG, null);
			mMapActivity.mMapBottomContent.setVisibility(View.VISIBLE);
			mMapActivity.mMapRightContent.setVisibility(View.VISIBLE);
			break;

		case R.id.redo_btn:
			reMeasure();
			break;
		case R.id.title_back:
			mMapActivity.removeFragment(TAG, null);
			mMapActivity.mMapBottomContent.setVisibility(View.VISIBLE);
			mMapActivity.mMapRightContent.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}

	@Override
	public void mapViewClickAnnotation(MapView mapView, Annotation annotation)
	{
		// TODO Auto-generated method stub

	}

	@Override
	public boolean mapViewWillShowAnnotationView(MapView mapView, AnnotationView annotationView)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean mapViewWillHideAnnotationView(MapView mapView, AnnotationView annotationView)
	{
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public AnnotationView mapViewViewForAnnotation(MapView mapView, Annotation annotation)
	{
		annotationView = new AnnotationView(annotation, getContext());
		annotationView.setPanToMapViewCenter(false);

		mCalloutView = LayoutInflater.from(getContext()).inflate(R.layout.annotation_calloutview, null);
		annotationView.setCalloutView(mCalloutView);

		ImageView closeCalloutView = (ImageView) mCalloutView.findViewById(R.id.close_iv);
		TextView title = (TextView) mCalloutView.findViewById(R.id.callout_titile_tv);
		title.setText("起点");
		// Annotation显示样式
		showAnnotationStyle(mAnnotationLst);
		if (mDotLst.size() == 1 && mStartAnnotation != null)
		{
			title.setText(mStartAnnotation.getTitle());
		}
		if (mDotLst.size() > 1 && annotation != null)
		{
			title.setText(annotation.getTitle());
		}
		closeCalloutView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (mDotLst.size() == 1)
				{
					reMeasure();
				}
				if (mDotLst.size() == 2)
				{
					mMapView.getAnnotationsOverlay().removeAnnotation(mAnnotationLst.get(mAnnotationLst.size() - 1));
					mAnnotationLst.remove(mAnnotationLst.size() - 1);
					mDotLst.remove(mDotLst.size() - 1);

					mAnnotationLst.get(mAnnotationLst.size() - 1).showAnnotationView();
				}
				if (mDotLst.size() > 3)
				{
					// 移除上一个Annotation
					mMapView.getAnnotationsOverlay().removeAnnotation(mAnnotationLst.get(mAnnotationLst.size() - 1));
					mAnnotationLst.remove(mAnnotationLst.size() - 1);
					mDotLst.remove(mDotLst.size() - 2);
					// mDotLst.size() == 3临界特殊值
					if (mDotLst.size() == 3)
					{
						mDotLst.remove(mDotLst.size() - 1);
					}
					mGraphicPolygon.setPoints(mDotLst);

					mAnnotationLst.get(mAnnotationLst.size() - 1).showAnnotationView();
				}
				mGraphicMultiPoint.setPoints(mDotLst);
				mGraphicPolyLine.setPoints(mDotLst);

			}
		});

		return annotationView;
	}

	@Override
	public void mapViewClickAnnotationView(MapView mapView, AnnotationView annotationView)
	{

	}

	/**
	 * 显示Annotation样式（最后一个红色，其余显示为的蓝色）
	 * 
	 * @param annotationLst
	 */
	private void showAnnotationStyle(List<Annotation> annotationLst)
	{
		if (annotationLst.size() > 1)
		{
			for (int i = 0; i < annotationLst.size() - 1; i++)
			{
				annotationLst.get(i).setImage(mBlueBmp);
			}
			annotationLst.get(annotationLst.size() - 1).setImage(mRedBmp);
		}
	}

	/**
	 * 获取绘制区面积
	 * 
	 * @param geoPolygon
	 * @return
	 */
	private String getArea(GeoPolygon geoPolygon)
	{
		String areaStr = "0.0平方米";
		DecimalFormat df = new DecimalFormat("###0.00");
		double area = geoPolygon.calArea(mMapView.getMap().getSRSInfo());
		if (area > 1000000)
		{
			areaStr = df.format(area / 1000000) + "平方千米";
		}
		else
		{
			areaStr = df.format(area) + "平方米";
		}
		return areaStr;
	}

	/**
	 * 重新测量
	 */
	private void reMeasure()
	{
		mGraphicMultiPoint.removeAllPoints();
		mGraphicPolygon.removeAllPoints();
		mGraphicPolyLine.removeAllPoints();
		mGraphicStartImg.setPoint(new Dot(0.0, 0.0));
		mMapView.getAnnotationsOverlay().removeAllAnnotations();
		// mGraphicText.setText("");
		mDotLst.clear();
		mDisLst.clear();
		mAnnotationLst.clear();
		mMapView.refresh();
	}

	@Override
	public void onDestroyView()
	{
		mMapView.setTapListener(null);
		mGraphicLayer.removeGraphic(mGraphicMultiPoint);
		mGraphicLayer.removeGraphic(mGraphicPolygon);
		// mGraphicLayer.removeGraphic(mGraphicText);
		mGraphicLayer.removeGraphic(mGraphicPolyLine);
		mGraphicLayer.removeGraphic(mGraphicStartImg);
		mMapView.getAnnotationsOverlay().removeAllAnnotations();

		mGraphicMultiPoint = null;
		mGraphicPolygon = null;
		mGraphicText = null;

		mMapView.forceRefresh();
		super.onDestroyView();
	}

	@Override
	public boolean goback()
	{
		return false;
	}

	@Override
	public boolean isLocked()
	{
		return false;
	}

	@Override
	public String getName()
	{
		return TAG;
	}

	/**
	 * 更新地图上添加的GraphicImage
	 * 
	 * @param graphicImage
	 * @param bitmap
	 * @param curPoint
	 */
	public void updateGraphicImg(GraphicImage graphicImage, Bitmap bitmap, Dot curPoint)
	{
		graphicImage.setImage(bitmap);
		graphicImage.setPoint(curPoint);
		graphicImage.setAnchorPoint(new PointF(0.5f, 0.0f));
	}

}
